import React, { useEffect, useState } from 'react'
import { Button, Card, Form, Input, Space, Table, message } from "antd";
import { SearchOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import type { ColumnsType, } from 'antd/es/table';
// 引入样式文件
import './index.css'
// 导入接口文件
import { FromFileType, HospitalSetItem } from '@/api/hospital/hospitalSet/type';
import { reqDeltedHospital, reqGetHosSetList, reqbatchMovenHospital } from '@/api/hospital/hospitalSet';
import { Link, useNavigate } from 'react-router-dom';
import { remove } from 'nprogress';
export default function Hospital() {

  // 导入navig函数(实现跳转页面)
  let navigate = useNavigate()

  // 设置状态
  let [hospitalitem, Sethospitalitem] = useState<HospitalSetItem[]>([])

  // 设置页码总数的状态
  let [total, Settotal] = useState(0)

  // 设置页码数的状态
  let [page, Setpage] = useState(1)

  // 设置每页显示数量的状态
  let [pageSize, SetpangeSize] = useState(5)

  // 设置loading的状态
  let [isLoading, SetIsLoading] = useState(false)

  // 获取form对象
  let [form] = Form.useForm();

  // 定义一个更新的状态
  let [update, Setupdate] = useState({});

  // 设置表单值的状态
  let [FromValue, SetFromValues] = useState<FromFileType>({
    hosname: '',
    hoscode: '',
  })

  // 定义选中医院id的状态
  let [select, setselect] = useState<React.Key[]>([])

  // 清空回调的函数
  let reset = () => {
    // // 设置from表单的值
    // form.setFieldsValue({ hosname: '', hoscode: '' });
    // // 更新状态
    // SetFromValues({ hosname: '', hoscode: '' })
    form.resetFields();
    // 跳到主页
    Setpage(1)
  }

  //表单提交的回调
  let onFinish = (values: FromFileType) => {
    //更新状态
    SetFromValues(values)
  };

  //失败的回调
  let onFinishFailed = () => { };


  // 删除医院数据的回调
  let remove = (id: React.Key) => {
    return async () => {
      await reqDeltedHospital(id)
      message.success('数据删除成功')
      Setupdate({});
    }
  }

  // 批量删除的回调
  let batchMoven = async () => {
    // console.log(111);
    await reqbatchMovenHospital(select as string[])
    // 删除成功的提醒
    message.success('批量删除操作成功!')
    // 渲染组件
    Setupdate({})

  }

  // 定义表格结构
  let columns: ColumnsType<HospitalSetItem> = [
    {
      title: '序号',
      render: (_, record, index) => {
        return index + 1;
      }
    },
    {
      title: '医院名称',
      dataIndex: 'hosname',
    },
    {
      title: '医院编号',
      dataIndex: 'hoscode',
    },
    {
      title: '基础路径',
      dataIndex: 'apiUrl',
    },
    {
      title: '签名',
      dataIndex: 'signKey',
    },
    {
      title: '联系人姓名',
      dataIndex: 'contactsName',
    },
    {
      title: '联系人电话',
      dataIndex: 'contactsPhone',
    },
    {
      title: '操作',
      width: 160,
      fixed: 'right',
      render: (_, record) => {
        return <Space>
          <Link to={`/syt/hospital/hospitalSet/edit/${record.id}`}>
            <Button type='primary' icon={<EditOutlined />}></Button>
          </Link>

          <Button onClick={remove(record.id)} type='primary' danger icon={<DeleteOutlined />}></Button>
        </Space>

      }
    },
  ]
  //准备测试数据
  // let data: HospitalSetItem[] = hospitalitem


  // useEffect 挂载
  useEffect(() => {
    SetIsLoading(true)
    //  声明异步函数
    let Datas = async () => {
      // 发送ajax 请求 调用函数
      let result = await reqGetHosSetList({
        page: page,
        limit: pageSize,
        hosname: FromValue.hosname,
        hoscode: FromValue.hoscode
      })
      Sethospitalitem(result.records)
      Settotal(result.total)
    }
    // 调用函数
    Datas()
    SetIsLoading(false)
  }, [page, pageSize, FromValue, update])

  return (

    <Card>
      {/* 1. 表单部分 */}
      <Form
        form={form}
        name="basic"
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
        layout="inline"
      >
        <Form.Item name="hosname">
          <Input placeholder="医院名称" />
        </Form.Item>

        <Form.Item name="hoscode">
          <Input placeholder="医院编号" />
        </Form.Item>

        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              查询
            </Button>

            <Button onClick={reset} >清空</Button>
          </Space>
        </Form.Item>
      </Form>
      {/* 2. 按钮 */}
      <div className='middle'  >
        <Button type='primary' className='btn1' onClick={() => navigate('/syt/hospital/hospitalSet/add')} >添加</Button>
        <Button type='primary' danger disabled={select.length === 0}
          onClick={batchMoven}
        >批量删除</Button>
      </div>
      {/* 3. 表格部分 */}
      <Table
        rowSelection={{
          type: 'checkbox',
          onChange: (selectedRowKeys: React.Key[], selectedRows: HospitalSetItem[]) => {
            // 更新选中状态
            // console.log(selectedRows)
            setselect(selectedRowKeys)
          }
        }}
        loading={isLoading}
        columns={columns}
        dataSource={hospitalitem}
        bordered
        rowKey={'id'}
        scroll={{
          x: 2000
        }}

        // 分页设置
        pagination={{
          // 总页数
          total: total,
          // 一页多少条数据
          pageSize: pageSize,
          // 当前在第几个
          current: page,
          showSizeChanger: true,
          pageSizeOptions: [5, 10, 15, 20],
          showQuickJumper: true,
          showTotal: total => {
            return `总计 :  ${total} 条 `;
          },
          // 当点击分页时,函数会调用
          onChange: (page: number, pageSize: number) => {
            // 更新页数和码数
            Setpage(page)
            SetpangeSize(pageSize)
          }

        }}

      />
    </Card>
  );
}

